#!/usr/bin/env echo "no"
# utf-8

#set -e

# run comman
# @param : info
# @param : e2e exit if error, default
# @param : cmd
function run {
  [ $# -gt 2 ] || return 1

  local info=${1}
  local e2e=${2}
  shift
  shift
  local cmd=$@ 

  #echo -n $info
  echo $info
  #echo -n $info ["$cmd"]
  echo "---------------------------------------"
  #eval "$cmd" >/dev/null 2>&1 && {
  eval "$cmd" && { echo "---------------------------------------"; echo " OK"; } || {
    echo "---------------------------------------"
    echo " Fail"
    [[ $e2e == "true" ]] && { return 1; } || :;
  }
}

# 配置特定仓库源
function myrepos { 
  echo "添加 epel 源"
  local D=/etc/yum.repos.d/epel.repo 
  sudo rm -f $D
  local ver=`cat /etc/redhat-release | sed -e "s/.*CentOS Linux release \([0-9]\+\).*/\1/"`
  sudo wget -O $D http://mirrors.aliyun.com/repo/epel-${ver}.repo
  #run "添加 epel 源" "true" \
  #sudo yum install -y epel-release
  #run "替换 epel 配置" "true" \
  #sudo sed -i -e "s:https:http:" \
  #sudo sed -i \
  #  -e "s:download.fedoraproject.org/pub:mirrors.aliyun.com:" \
  #  -e "s/^mirrorlist/#mirrorlist/" \
  #  -e "s/^#baseurl/baseurl/" \
  #  /etc/yum.repos.d/epel.repo
  #sudo rm -f /etc/yum.repos.d/epel-*.repo || :;
}

# 确保工具存在，不存在就安装
function need {
  local cmd=$1
  local ins=${2:-"$1"}
  run "安装 [$cmd]" "true" \
  hash $cmd 2\>/dev/null \|\| sudo yum install -y $ins
}

# git clone or pull
# @param : dir
# @param : url
function git_sync {
  local dir=$1
  local url=$2
  [[ -d $dir && -d $dir/.git ]] && { 
    cd $dir;
    run "同步 $url $dir" "true" \
    git pull
    :; 
  } || {
    [[ -e $dir ]] && { 
      echo "$dir is exists"; 
      exit 1; 
    }
    run "同步 $url $dir" "true" \
    git clone $url $dir
  }
}

# 把指定文件从base目录拷贝到home目录
# @param file or dir
# @base $W
function base_to_home {
  local f=${1}
  local d=$(dirname $f)
  [ -f $W/base/$f ] && { 
    run "同步脚本 $W/base/$f" "true" \
    mkdir -p ~/$d \&\& cat $W/base/$f \> ~/$f 
  } || {
    [ -d $W/base/$f ] && {
      for sd in `ls $W/base/$f`; do
        base_to_home $f/$sd
      done
    } || :;
  }
}

